import { FIELD_TYPES } from "@/common/constants";
import DynamicList from "@/components/dynamicList";
import { Input, Card, Select, Form, Button } from "antd";
import { getList as fieldList } from "@/pages/model/fields/api";
import { useCallback, useEffect, useState } from "react";

const RenderChildrenComponent = ({ onDelete, index, value, onChangeItem }) => {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue(value);
  }, [value]);

  return (
    <Card
      title={`字段${index + 1}`}
      extra={
        <Button type="link" onClick={onDelete}>
          删除
        </Button>
      }
      style={{ width: "100%" }}
    >
      <Form
        form={form}
        onValuesChange={(_, values) => {
          onChangeItem?.(values);
        }}
      >
        <Form.Item rules={[{ required: true }]} label="字段类型" name="type">
          <Select options={FIELD_TYPES} />
        </Form.Item>
        <Form.Item label="字段名称" name="label">
          <Input />
        </Form.Item>
        <Form.Item label="字段Key" name="name">
          <Input />
        </Form.Item>
        <Form.Item label="字段Key" hidden name="fieldId">
          <Input />
        </Form.Item>
      </Form>
    </Card>
  );
};
export default () => {
  const [list, setList] = useState([]);
  const getData = useCallback(async () => {
    const res = await fieldList();
    const { code, data } = res;
    if (code === 0) {
      setList(
        data?.list?.map((item) => ({ label: item?.name, value: item?.id }))
      );
    }
  }, []);
  useEffect(() => {
    getData();
  }, [getData]);
  return [
    {
      label: "模型名称",
      id: "name",
      type: "text",
    },
    {
      label: "字段添加",
      id: "list",
      renderFieldItem: () => (
        <DynamicList<Record<string, any>>
          childrenComponent={({ value, onDelete, onChangeItem, index }) => (
            <RenderChildrenComponent
              value={value}
              index={index}
              onDelete={onDelete}
              onChangeItem={onChangeItem}
            />
          )}
        />
      ),
    },
    {
      label: "id",
      id: "id",
      type: "text",
      formItemProps: {
        hidden: true,
      },
    },
  ];
};
